import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { ErrorBlock, Skeleton, Empty, NavBar, SwipeAction } from 'antd-mobile'
import { DeleteOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'

export type MyTraining = {
  id?: number | string
  name: string
  level?: string
  equipments?: string[]
  parts?: string[]
  warmup?: boolean
  stretch?: boolean
  createdAt?: number
}

export default function SetMy() {
  const navigate = useNavigate()
  const [list, setList] = useState<MyTraining[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)


  const load = async () => {
    try {
      setError(null)
      setLoading(true)
      const { data } = await axios.get<MyTraining[]>('/api/mytrainings')
      setList(Array.isArray(data) ? data : [])
    } catch (e: any) {
      setError(e?.message || '加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    load()
  }, [])


  const openDetail = (item: MyTraining, idx: number) => {
    const id = (item.id ?? idx).toString()
    navigate(`/mytraining/setmy/${encodeURIComponent(id)}`)
  }

  const handleDelete = async (item: MyTraining, idx: number) => {
    const id = item.id ?? idx
    try {
      await axios.delete(`/api/mytrainings/${id}`)
    } catch (e) {
      // 即使删除失败，也先更新前端，避免交互卡住；实际环境可做重试/提示
    } finally {
      setList((prev) => prev.filter((it, i) => (item.id != null ? it.id !== item.id : i !== idx)))
    }
  }

  return (
    <div className="setmy-wrap">
      <NavBar onBack={() => navigate(-1)} style={{ background: 'rgb(227, 83, 26)', color: '#fff' }}>我的训练</NavBar>

      <div className="content">
        {loading && (
          <div className="loading">
            {Array.from({ length: 5 }).map((_, i) => (
              <Skeleton animated key={i} />
            ))}
          </div>
        )}

        {!loading && error && (
          <ErrorBlock status="default" title="加载失败" description={error} />
        )}

        {!loading && !error && (
          list.length === 0 ? (
            <Empty description="暂无训练记录" />
          ) : (
            <div className="cards-col">
              {list.map((it, idx) => (
                <SwipeAction
                  key={it.id ?? idx}
                  rightActions={[
                    {
                      key: 'delete',
                      color: 'danger',
                      text: (
                        <div className="del-action">
                          <DeleteOutline />
                          <span>删除</span>
                        </div>
                      ),
                      onClick: () => handleDelete(it, idx),
                    },
                  ]}
                >
                  <div className="card" onClick={() => openDetail(it, idx)}>
                    {it.name}
                  </div>
                </SwipeAction>
              ))}
            </div>
          )
        )}
      </div>

      <style>{`
        .setmy-wrap {
          min-height: 100vh;
          width: 100%;
          display: flex;
          flex-direction: column;
          background-image:
            linear-gradient(180deg, rgba(255,255,255,0.75) 0%, rgba(255,255,255,0.75) 100%),
            url('/比心.png');
          background-size: cover;
          background-position: center;
          background-attachment: fixed;
        }
        .content { padding: 16px; flex: 1; display: flex; }
        .cards-col {
          margin: 0 auto;
          width: min(720px, 92vw);
          display: flex;
          flex-direction: column;
          gap: 12px;
        }
        .card {
          width: 100%;
          min-height: 64px;
          border-radius: 12px;
          background: rgb(227, 83, 26);
          color: #fff;
          font-weight: 700;
          font-size: 18px;
          display: flex;
          align-items: center;
          justify-content: center;
          letter-spacing: 0.5px;
          box-shadow: 0 6px 18px rgba(0,0,0,0.16);
          border: none;
          cursor: pointer;
          user-select: none;
        }
        .card:active { transform: scale(0.995); }
        .loading { width: min(720px, 92vw); margin: 0 auto; display: grid; gap: 12px; }
        .del-action { display: flex; align-items: center; gap: 6px; padding: 0 8px; }

        /* 计时器弹窗样式 */
        .timer-overlay {
          position: fixed;
          inset: 0;
          background: rgba(0,0,0,0.45);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 1000;
        }
        .timer-modal {
          width: min(360px, 90vw);
          border-radius: 16px;
          background: #fff;
          padding: 20px 16px 16px;
          box-shadow: 0 12px 40px rgba(0,0,0,0.25);
          text-align: center;
        }
        .timer-title {
          font-size: 16px;
          font-weight: 700;
          color: #333;
          margin-bottom: 8px;
        }
        .timer-clock {
          font-size: 48px;
          font-weight: 800;
          color: #FF6B35;
          letter-spacing: 1px;
          margin: 6px 0 14px;
        }
        .timer-actions { display: flex; gap: 12px; margin-bottom: 8px; }
        .btn {
          flex: 1;
          height: 44px;
          border-radius: 22px;
          border: none;
          cursor: pointer;
          font-size: 15px;
          font-weight: 700;
        }
        .btn.primary { background: #FF6B35; color: #fff; }
        .btn.secondary { background: #fff; color: #FF6B35; border: 2px solid #FF6B35; }
        .timer-tip { color: #999; font-size: 12px; }
      `}</style>
    </div>
  )
}
